<?php

namespace App\Admin\Repositories;

use App\Models\Firm as Model;
use Dcat\Admin\Form;
use Dcat\Admin\Repositories\EloquentRepository;

class Firm extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;


    public function store(Form $form)
    {

        $updates = $form->updates();


        if ($updates['consult_time']>0 && $updates['consult_time']>time()){
            $updates['is_warn'] = 1;
        }


        $firm = Model::query()->create($updates);
        $firm->profile()->create($updates['profile']);

        return $firm->getKey();
    }


    public function update(Form $form)
    {
        $updates = $form->updates();


        $firm = Model::query()->with('profile')->where('id',$form->getKey())->first();


        if ($updates['consult_time']>0 && $updates['consult_time']>time()){
            $updates['is_warn'] = 1;
        }

        foreach ($firm->getFillable() as $value){
            if (isset($updates[$value])){
                $firm->{$value} = $updates[$value] ?? '';
            }
        }
        $firm->save();


        if (empty($firm->profile)){
            $updates['profile']['firm_id'] = $firm->getKey();
            \App\Models\FirmProfile::query()->create($updates['profile']);
        }else{
            foreach ($firm->profile->getFillable() as $item){

                if (isset($updates['profile'][$item])){
                    $firm->profile->{$item} = $updates['profile'][$item] ?? '';
                }

            }
            $firm->profile->save();
        }

        return true;
    }
}
